package com.hnkywl.sts.dao.organ;

import com.hnkywl.sts.entity.organ.Lj;
import com.hnkywl.sts.util.Pager;
import com.hnkywl.sts.util.QuerySearcher;
import net.ruixin.orm.hibernate.Page;
import net.ruixin.orm.hibernate.SimpleHibernateTemplate;
import org.hibernate.SQLQuery;
import org.hibernate.transform.AliasToEntityMapResultTransformer;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;


/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-3-22
 * Time: 下午4:31
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class LjwhDao extends SimpleHibernateTemplate<Lj, Long> {
    public Page<Lj> findAll(Pager pager, QuerySearcher queryLj) {
        String where = queryLj == null ? "" : queryLj.getHql();
        pager.setTotal(this.findLong("select count(distinct lj) from Lj lj left join lj.sy sy left join lj.xy xy" + where ).intValue());;
        return this.find(pager.getPage(), "select distinct lj from Lj lj left join lj.sy sy left join lj.xy xy" + where + " order by lj.dateCreated desc");
    }

    public List<Lj> findAll(QuerySearcher queryLj) {
            String where = queryLj == null ? "" : queryLj.getHql();
            return this.find("select lj from Lj lj" + where + " and lj.sfdj = false and lj.zt = 'ysp' order by lj.dateCreated desc");
    }
    public List<Lj> findAll() {
        //  String where = queryLj == null ? "" : queryLj.getHql();
        return this.find("select lj from Lj lj where lj.sfdj = false and lj.zt = 'ysp' order by lj.dateCreated desc");
    }



    /**
     * 根据条件找到所有的上游或下游
     *
     * @param lx     路径类型
     * @param jyjgId 经营机构Id
     * @param sxy    上下游
     * @return
     */
    public List<Map> findAllQyjg(String lx, String jyjgId, String sxy) {
        String sql = "select distinct  qyjg.id as \"id\",qyjg.jc as \"jc\" from t_sys_lj lj " +
                "left join t_sys_gsjg jyjg on (lj.jyjg_id = jyjg.id) " +
                "left join t_lj_@sxy @sxy on(lj.id = @sxy.lj_id) " +
                "left join t_sys_gsjg qyjg on (@sxy.@sxy_id = qyjg.id)";
        sql = sql.replaceAll("@sxy", sxy);
        StringBuilder where = new StringBuilder();
        where.append(" lj.lx =:lx ");
        if (jyjgId != null && !jyjgId.isEmpty())
            where.append(" and jyjg.id =:jyjgId ");
        SQLQuery sqlQuery = getSession().createSQLQuery(sql + " where " + where);
        sqlQuery.setString("lx", lx);
        if (jyjgId != null && !jyjgId.isEmpty())
            sqlQuery.setString("jyjgId", jyjgId);
        sqlQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
        return sqlQuery.list();
    }

}
